/*
* 材料收料单列表
* */

import 'dart:convert';

import 'package:center_beijing/api/material_science_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/pull_select_widget.dart';
import 'package:center_beijing/widgets/search_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class MaterialWarehousing extends StatefulWidget {
  @override
  _MaterialWarehousingState createState() => _MaterialWarehousingState();
}

class _MaterialWarehousingState extends State<MaterialWarehousing>
    with SingleTickerProviderStateMixin {
  EasyRefreshController _controller = EasyRefreshController();
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;
  List<SelectItems> typeList = [
    SelectItems(label: '全部类型', value: ''),
    SelectItems(label: '收料', value: '1'),
    SelectItems(label: '退料', value: '2')
  ];
  SelectItems selectType = SelectItems(label: '全部类型', value: '');
  TextEditingController _textInput = TextEditingController();
  List<SelectItems> factoriesList = [SelectItems(label: '全部供应商', value: '')];
  SelectItems selectFactory = SelectItems(label: '全部供应商', value: '');

  @override
  void initState() {
    super.initState();
    bus.on('refreshReceiveList', (arg) {
      page = 1;
      this.getAllReceived();
    });
    this.getAllSupplier();
  }

  /*
  * 获取供应商
  * */
  getAllSupplier() async {
    var result =
        await getSupplier({'sectionId': GlobalConfig.selectFactory.tag});
    if (result != null) {
      List<SelectItems> tem = [SelectItems(label: '全部供应商', value: '')];
      result.forEach((item) {
        tem.add(SelectItems(
            label: item['supplierName'], value: item['corpId'], dict: item));
      });
      this.setState(() {
        factoriesList = tem;
      });
    }
    LogUtil.d(result);
  }

  /*
  * 获取收料单列表
  * */
  getAllReceived() async {
    var pass = {
      'queryFields': json.encode([
        {
          "columnName": 'projectSectionId',
          "dataType": "string",
          "operator": "=",
          "queryValue": GlobalConfig.selectFactory.tag
        },
        {
          "columnName": "docNumber",
          "dataType": "string",
          "operator": "like",
          "queryValue": _textInput.text
        },
        {
          "columnName": "receiptType",
          "dataType": "string",
          "operator": "like",
          "queryValue": selectType.value
        },{"columnName":"supplierCorporationId","dataType":"string","operator":"=","queryValue":selectFactory.value}
      ]),
      'page': page,
      'limit': pageSize,
    };
    var result = await getReceivedEntryExList(pass);
    loading.dismiss();
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null && result['hasError'] == null) {
      this.setState(() {
        if (result['results'].length == 0) {
          _controller.finishLoad(success: true, noMore: true);
        } else {
          dataSource.addAll(result['results']);
          if (dataSource.length == result['totalRecordNum']) {
            _controller.finishLoad(success: true, noMore: true);
          }
        }
      });
    } else {
      _controller.finishLoad(success: true);
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    bus.off('refreshReceiveList');
    super.dispose();
  }

  /*
  * 删除收料单
  * */
  deleteMaterial(value) async {
    loading.show(delay: 30);
    var result = await deleteReceivedSheet({'id': value['id']});
    loading.dismiss();
    if (result != null && result['hasError'] == null) {
      Fluttertoast.showToast(msg: '删除成功');
      page = 1;
      this.getAllReceived();
    } else {
      Fluttertoast.showToast(msg: result['errorMessage']);
    }
    LogUtil.d(result);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('收料单'),
        ),
        body: Container(
          color: Styles.MainBackgroundColor,
          padding: EdgeInsets.fromLTRB(
              0, 0, 0, MediaQuery.of(context).padding.bottom + 70),
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.fromLTRB(Styles.spacing16, Styles.spacing8,
                    Styles.spacing16, Styles.spacing8),
                child: SearchWidget(
                  textInput: _textInput,
                  placeholder: '请输入单号',
                  textSubmit: (value) {
                    page = 1;
                    // _controller.finishLoad(success: true, noMore: false);
                    this.getAllReceived();
                  },
                ),
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(Styles.spacing16, Styles.spacing4,
                    Styles.spacing16, Styles.spacing4),
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Container(
                        color: Colors.white,
                        child: PullSelectWidget(
                          text_align: TextAlign.center,
                          rightText: selectFactory.label,
                          backColor: Colors.white,
                          items: factoriesList,
                          selectCallback: (value) {
                            this.selectFactory = value;
                            page = 1;
                            loading.show(delay: 15);
                            this.getAllReceived();
                          },
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Container(
                        color: Colors.white,
                        child: PullSelectWidget(
                          text_align: TextAlign.center,
                          rightText: selectType.label,
                          backColor: Colors.white,
                          items: typeList,
                          selectCallback: (value) {
                            this.selectType = value;
                            page = 1;
                            loading.show(delay: 15);
                            this.getAllReceived();
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                  child: EasyRefresh.custom(
                      shrinkWrap: true,
                      firstRefresh: true,
                      controller: _controller,
                      header: MaterialHeader(),
                      footer: ClassicalFooter(
                          loadingText: '加载中',
                          loadText: '上拉加载',
                          noMoreText: '没有更多数据',
                          loadedText: '加载完成',
                          infoText: '更新于 %T',
                          textColor: Styles.NoMoreColor,
                          showInfo: false),
                      emptyWidget: (dataSource.length == 0 && !firstLoad)
                          ? Center(
                              child: Image(
                                image: AssetImage('assets/images/no_data.png'),
                                width: 128,
                                height: 150,
                              ),
                            )
                          : null,
                      onRefresh: () async {
                        _controller.finishLoad(success: true, noMore: false);
                        if (mounted) {
                          page = 1;
                          this.getAllReceived();
                        }
                      },
                      onLoad: () async {
                        await Future.delayed(Duration(seconds: 2), () {
                          if (mounted) {
                            page++;
                            this.getAllReceived();
                          }
                        });
                      },
                      slivers: <Widget>[
                    SliverList(
                      delegate: SliverChildBuilderDelegate(
                        (context, index) {
                          return GestureDetector(
                            onTap: () {
                              Get.toNamed(
                                  RouteConfig.materialWarehousingDetailList,
                                  arguments: this.dataSource[index]);
                            },
                            child: Container(
                              color: Colors.white,
                              margin:
                                  EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                              padding: EdgeInsets.fromLTRB(
                                  Styles.spacing12,
                                  Styles.spacing8,
                                  Styles.spacing12,
                                  Styles.spacing8),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '单据编号  ${this.dataSource[index]['docNumber']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '收料类型  ${this.dataSource[index]['receiptType'] == '1' ? '收料' : '退料'}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '供 应 商  ${this.dataSource[index]['corpName']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '收料时间  ${this.dataSource[index]['receiptDateStr']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '收 料 人  ${this.dataSource[index]['receiver']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, Styles.spacing4, 0, Styles.spacing4),
                                    child: Text(
                                      '仓   库  ${this.dataSource[index]['houseName']}',
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ),
                                  Row(
                                    children: [
                                      Expanded(
                                          child: GestureDetector(
                                        onTap: () {
                                          Get.toNamed(
                                              RouteConfig
                                                  .editMaterialWarehousing,
                                              arguments:
                                                  this.dataSource[index]);
                                        },
                                        child: Container(
                                          padding:
                                              EdgeInsets.all(Styles.spacing8),
                                          margin:
                                              EdgeInsets.all(Styles.spacing8),
                                          decoration: BoxDecoration(
                                              border: Border.all(
                                                  color: Styles.BlueColor,
                                                  width: 1)),
                                          alignment: Alignment.center,
                                          child: Text(
                                            '编辑',
                                            style: TextStyle(
                                                color: Styles.BlueColor,
                                                fontSize: Styles.NormalFont),
                                          ),
                                        ),
                                      )),
                                      Expanded(
                                          child: GestureDetector(
                                        onTap: () {
                                          FocusScope.of(context).requestFocus(new FocusNode());
                                          showDialog(
                                              barrierDismissible: false,
                                              context: this.context,
                                              builder: (BuildContext context) {
                                                return AlertDialog(
                                                  title: Text('注意'),
                                                  content: Text('确认删除吗？'),
                                                  actions: <Widget>[
                                                    new Container(
                                                      child: FlatButton(
                                                        child: new Text(
                                                          "取消",
                                                          style: TextStyle(
                                                              color:
                                                                  Colors.black),
                                                        ),
                                                        onPressed: () {
                                                          Navigator.pop(
                                                              context);
                                                        },
                                                      ),
                                                    ),
                                                    new Container(
                                                      child: FlatButton(
                                                        child: new Text(
                                                          "确定",
                                                          style: TextStyle(
                                                              color:
                                                                  Colors.red),
                                                        ),
                                                        onPressed: () {
                                                          Navigator.pop(
                                                              context);
                                                          this.deleteMaterial(
                                                              this.dataSource[
                                                                  index]);
                                                        },
                                                      ),
                                                    ),
                                                  ],
                                                );
                                              });
                                        },
                                        child: Container(
                                          padding:
                                              EdgeInsets.all(Styles.spacing8),
                                          margin:
                                              EdgeInsets.all(Styles.spacing8),
                                          decoration: BoxDecoration(
                                              border: Border.all(
                                                  color: Styles.RedColor,
                                                  width: 1)),
                                          alignment: Alignment.center,
                                          child: Text(
                                            '删除',
                                            style: TextStyle(
                                                color: Styles.RedColor,
                                                fontSize: Styles.NormalFont),
                                          ),
                                        ),
                                      )),
                                    ],
                                  )
                                ],
                              ),
                            ),
                          );
                        },
                        childCount: dataSource.length,
                      ),
                    ),
                  ]))
            ],
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                Get.toNamed(RouteConfig.addMaterialWarehousing);
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '新增收料单',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
